import React, { ReactDOM, ReactElement } from "react";
import { FC } from "react";
import { PropsWithChildren } from "react";

interface IndexProps {
  visible: boolean;
  removeOnLeave?: boolean;
}

function Comp(props: any) {
  const { children, visible, removeOnLeave } = props;
  const renderedRef = React.useRef(visible);
  if (visible) {
    renderedRef.current = true;
  }

  let tabChildren: React.ReactNode;
  if (!children) {
    tabChildren = null;
  } else {
    if (visible) {
      tabChildren = children();
    } else if (renderedRef.current && !removeOnLeave) {
      tabChildren = children({ style: { display: "none" } });
    } else if (removeOnLeave) {
      tabChildren = null;
    }
  }

  return tabChildren;
}
const Index: FC<PropsWithChildren<IndexProps>> = (props) => {
  const { children, removeOnLeave, visible } = props;

  return (
    <Comp removeOnLeave={removeOnLeave} visible={visible}>
      {(props: any) => {
        return React.cloneElement(children as ReactElement, {
          ...props,
        });
      }}
    </Comp>
  );
};

export default Index;
